﻿using EleCho.GoCqHttpSdk;
using Microsoft.Extensions.Logging;
using PluginSdk;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;

namespace ManualPlugin;

public class Manual(ConcurrentDictionary<string, string> manuals) : IPlugin
{
    public string Name => "手册";

    public string Description => "命令手册";

    public ICommandBase[] Commands { get; set; } = [];

    public ILoggerFactory LoggerFactory { get; set; }

    public ConcurrentDictionary<string, string> Manuals = manuals;

    public void ConfigLogger(ILoggerFactory loggerFactory)
    {
        LoggerFactory = loggerFactory;
    }

    public void Config()
    {
        Commands = [new ManualCommand(LoggerFactory.CreateLogger<ManualCommand>(), Manuals)];
    }

    public void ConfigSession(ICqActionSession session)
    {
    }
}

public class ManualCommand(ILogger logger, ConcurrentDictionary<string, string> Manuals) : ITextCommand
{
    public string Match => "^#(手册|manual|man)";

    public string Name => "手册";

    public string Description => "命令手册";

    public Permission Permission => Permission.SameUser;

    private readonly ILogger logger = logger;

    public async Task Handler(IMessageStream stream)
    {
        var msg = await stream.ReadMessage();
        if (msg == null)
        {
            logger.LogWarning("错误：读取消息为空");
            await stream.WriteMessage(new("您好像没有指定手册页，想看什么？例子：试试#手册 手册"));
            return;
        }
        else
        {
            var command = Regex.Match(msg.Message.Text, "#(手册|manual|man)[ \n\r]*(.*)").Groups[2].Value;
            if (command != null && Manuals.TryGetValue(command, out string? value))
            {
                await stream.WriteMessage(new(value));
                return;
            }
            else
            {
                logger.LogWarning($"错误：找不到手册页：{command}");
                await stream.WriteMessage(new($"找不到手册页：{command}"));
                return;
            }
        }
    }
}